package mysql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import objects.Music;
import objects.Person;

public class MusicQueries {
	
	private static final String DATABASE_URL = "jdbc:mysql://localhost/MovieBase";
	private static final String USERNAME = "moviebase";
	private static final String PASSWORD = "moviebase";

	private Connection connection = null;
	private PreparedStatement selectAllMusic = null;
	private PreparedStatement insertNewMusic = null;
	private PreparedStatement checkoutMusic = null;

	public MusicQueries() {
		try {
			connection = DriverManager.getConnection(DATABASE_URL, USERNAME,
					PASSWORD);

			selectAllMusic = connection
					.prepareStatement("SELECT * FROM Music");

			insertNewMusic = connection
					.prepareStatement("INSERT INTO Music (muid, artist, album, location) VALUES "
							+ "(?,?,?,?)");
			
			checkoutMusic = connection
					.prepareStatement("UPDATE `MovieBase`.`Music` SET `out`=? WHERE `muid`=?");
		} catch (SQLException e) {
			System.out.println(e);
		}
	}

	public List<Music> getAllMusic() {
		List<Music> results = null;
		ResultSet resultSet = null;

		try {
			resultSet = selectAllMusic.executeQuery();
			results = new ArrayList<Music>();

			while (resultSet.next()) {
				results.add(new Music(resultSet.getInt("muid"), resultSet.getString("artist"),
						resultSet.getString("album"), resultSet
								.getInt("location"), resultSet.getInt("out")));
			}
		} catch (SQLException e) {
			System.out.println(e);
		} finally {
			try {
				resultSet.close();
			} catch (SQLException e) {

			}
		}
		return results;
	}
	
	public int addMusic(int muid, String artist, String album, int loc, int out) {
		int result = 0;
		
		try {
			insertNewMusic.setInt(1, muid);
			insertNewMusic.setString(2, artist);
			insertNewMusic.setString(3, album);
			insertNewMusic.setInt(4, loc);
			
			result = insertNewMusic.executeUpdate();
		}
		catch (SQLException e) {
			System.out.println(e);
			close();
		}
		
		return result;
	}
	
	public void close() {
		try {
			connection.close();
		}
		catch (SQLException e) {
			System.out.println(e);
		}
	}

	public int checkoutMovie(int moid, int out) {
		int result = 0;

		try {
			checkoutMusic.setInt(1, out);
			checkoutMusic.setInt(2, moid);

			result = checkoutMusic.executeUpdate();
		} catch (SQLException e) {
			System.out.println(e);
			close();
		}

		return result;
	}
}
